/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.it;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import ru.irenproject.ModifierList;
import ru.irenproject.Profile;
import ru.irenproject.TestInputException;
import ru.irenproject.store.Store;

@Singleton public final class ItInput {
  private final ItReaderFactory fReaderFactory;

  @Inject ItInput(ItReaderFactory readerFactory) {
    fReaderFactory = readerFactory;
  }

  public void read(Path in, Store store, ItConsumer consumer) {
    try {
      try (ZipFile zip = new ZipFile(in.toFile())) {
        ZipEntry entry = zip.getEntry(It.IT_TEST_FILE_NAME);
        ItCheck.input(entry != null);
        Document document;
        try (InputStream xmlIn = zip.getInputStream(entry)) {
          DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
          document = db.parse(xmlIn);
        }
        consumer.consume(fReaderFactory.create(zip, document.getDocumentElement(), store));
      }
    } catch (ZipException | SAXException | TestInputException e) {
      throw new ItInputException(e);
    } catch (IOException | ParserConfigurationException e) {
      throw new RuntimeException(e);
    }
  }

  public void readFromBytes(byte[] bytes, Store store, ItConsumer consumer) {
    try {
      Path temp = Files.createTempFile(null, null);
      try {
        Files.write(temp, bytes);
        read(temp, store, consumer);
      } finally {
        Files.delete(temp);
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public void bytesToModifierList(byte[] bytes, final ModifierList list) {
    readFromBytes(bytes, list.store(), new ItConsumer() {
      @Override public void consume(ItReader in) {
        Element xmlModifiers = XmlUtils.getChild(in.root(), It.ELEM_MODIFIERS);
        if (xmlModifiers == null) {
          list.clear();
        } else {
          in.readModifiers(xmlModifiers, list);
        }
      }
    });
  }

  public void bytesToProfile(byte[] bytes, final Profile profile) {
    readFromBytes(bytes, profile.store(), new ItConsumer() {
      @Override public void consume(ItReader in) {
        in.readProfile(XmlUtils.findChild(in.root(), It.ELEM_PROFILE), profile);
      }
    });
  }
}
